﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace PaPaPa.Chat
{
    [Authorize]
    public class ChatHub : Hub
    {
        private readonly static Dictionary<string, string> _dicUser = new Dictionary<string, string>();

        public override System.Threading.Tasks.Task OnConnected()
        {
            AddOrUpdateConnection();

            return base.OnConnected();
        }

        public override System.Threading.Tasks.Task OnReconnected()
        {
            AddOrUpdateConnection();

            return base.OnReconnected();
        }

        private void AddOrUpdateConnection()
        {
            if (!_dicUser.ContainsKey(this.Context.User.Identity.Name))
            {
                _dicUser.Add(this.Context.User.Identity.Name, this.Context.ConnectionId);
            }
            else
            {
                _dicUser[this.Context.User.Identity.Name] = this.Context.ConnectionId;
            }
        }

        public override System.Threading.Tasks.Task OnDisconnected()
        {
            _dicUser.Remove(this.Context.User.Identity.Name);

            return base.OnDisconnected();
        }

        public void SendPublic(string message)
        {
            Clients.All.receivePublic(this.Context.User.Identity.Name, message);
        }

        public void SendPrivate(string toName, string message)
        {
            var receiver = new string[] { _dicUser[this.Context.User.Identity.Name], _dicUser[toName] };
            Clients.Clients(receiver).receivePrivate(this.Context.User.Identity.Name, message);
        }
    }
}